from SpcDriver.spcserial import SpcSerial
import threading

class SpcProtocol(SpcSerial):

    task = threading.Thread()
    __TaskIsRun = False

    r_data = ''
    r_len = 0

    def __init__(self,name, port, baud):
        super().__init__(name, port, baud)
        self.task = threading.Thread(target=self.__task_enter, name = 'ProtocolTask', args=None)
        return

    def __task_enter(self):

        while self.__TaskIsRun:
            # step.1 接收数据包
            (self.r_data, self.r_len) = self.ReadLine()
            # step.2 解析数据包
            (cont, size, type) = self.__Unpackage(self.r_data, self.r_len)


            continue
        print("The thread is end >> " + self.task.getName())
        return

    def __Unpackage(self, pack = '', len = 0):
        dataContent = []
        dataType = -1
        dataSize = -1
        result = (dataContent, dataSize, dataType)
        if pack == '' or len < 4:
            print("package error\n")
            return result
        # step.1 judge the head of package  ">"
        if pack[0] != '>':
            print("pack error in head \n")
            return result
        #

        return result

    def StartTask(self):
        self.__TaskIsRun = True
        self.task.start()
        return

    def StopTask(self):
        self.__TaskIsRun = False
        self.task.join()
        return
